# -*- coding: utf-8 -*
import os
import inspect
import MyClasses.MyConfigParser
import imaplib

class MyMailer:

	PROV_NAME = ''

	def __init__( self, conf_parser ):
		self.config = conf_parser
		self.PROV_NAME = conf_parser.getSection()

	def connect(self, debug = 0):
		self.imap = imaplib.IMAP4_SSL(self.config.getHost(), self.config.getPort())
		self.imap.debug = debug

	def login( self ):
		self.imap.login( self.config.getUser(), self.config.getPass() )
		if self.imap.select( )[0] != 'OK':
			raise imaplib.IMAP4.error("Не могу выбрать INBOX")

	def search(self, needle, date):
		search_result = self.imap.search( 'UTF-8', 'SUBJECT', needle, 'ON', date)
		if search_result[0] != 'OK':
			raise imaplib.IMAP4.error("Не удалось выполнить поиск [SUBJECT]:"+needle+" [ON]:"+date)

		if search_result[1][0] is not None and len(search_result[1][0])>0:	
			return [ self.fetch( id ) for id in search_result[1][0].split(' ') ]
		else:
			return False

	def fetch( self, id ):
		return ( self.imap.fetch( id, '(BODY[HEADER])')[1][0][1], self.imap.fetch( id, '(BODY[TEXT])')[1][0][1] )

	def output(self, enum):
		print "\n"
		print self.PROV_NAME
		print "================================="
		print "\n"
		if not enum:
			print "No messages found"

		else:
			for message in enum:
				self.out_mail( message )
			
		print "\n"
		
	def out_mail( self, message):
		print message[0]
		print "\n"
		print message[1]
		print "\n"